package etc;

import java.io.File;
import java.util.ArrayList;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Utils {

	static public Boolean isValidIP( String ipString ) {
		// Original source for below regex: http://www.regular-expressions.info/examples.html
		return ipString.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b");
	}

	static public ArrayList<File> listFilesInDir(String localPath) {
		return listFilesInDir( new File(localPath) );
	}

	static public ArrayList<File> listFilesInDir( File searchFile ) {
		ArrayList<File> retList = new ArrayList<File>();

		if( searchFile != null ) {
			if( searchFile.isDirectory() ) {
				File[] fileList = searchFile.listFiles();
				if( fileList != null ) {
					for( File f : fileList ) {
						retList.addAll( listFilesInDir(f) );
					}
				}
			}else{
				retList.add( searchFile );
			}
		}

		return retList;
    }

	static public String fileListToXMLString( ArrayList<File> fileList, File rootFolder ) {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("fileList");

		for (File file : fileList) {
			Element temp = root.addElement("file");
			temp.addAttribute("path", rootFolder.toURI().relativize(file.toURI()).getPath());
			temp.addAttribute("lastModified", Long.toString( file.lastModified() ) );
			temp.addAttribute("size", Long.toString( file.length() ) );
		}

		return doc.asXML().replace('\n', ' ');
	}
	
}
